package com.sktlab.bizconfmobile.util;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.sktlab.bizconfmobile.R;
import com.sktlab.bizconfmobile.customview.LoadingDialog;
import com.sktlab.bizconfmobile.interfaces.ILoadingDialogCallback;

public class LoadingDialogUtil {
	
	private Activity mActivity;	
	private LoadingDialog mDialog;
	private ILoadingDialogCallback mCallback;
	
	private final int SHOW_DIALOG = 1;
	private final int CLOSE_DIALOG_SUCCESS = 2;
	private final int CLOSE_DIALOG_ERROR = 3;
	
	private final String KEY_OF_MSG = "msg";
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
			switch(msg.what) {
			
			case SHOW_DIALOG:
				
				Bundle data = msg.getData();
				
				String message = data.getString(KEY_OF_MSG);
				
				finishDialog();
				
				showLoadingDialog(message);
				
				break;
				
			case CLOSE_DIALOG_SUCCESS:
				
				finishDialog();
				
				if(mCallback != null) {
					
					mCallback.onSuccessDone();
				}
				
				break;
				
			case CLOSE_DIALOG_ERROR:	
				
				finishDialog();	
				
				if(mCallback != null) {
					
					mCallback.onDoneWithError();
				}
				
				break;	
			}
		}	
	};
	
	public LoadingDialogUtil(Activity activity, ILoadingDialogCallback callback) {
		
		mActivity = activity;
		mDialog = new LoadingDialog(mActivity, R.layout.loading_dialog);
		setCallback(callback);
	}
	
	public void showDialog(String toastText) {
		
		Message msg = new Message();				
		Bundle data = new Bundle();
		data.putString(KEY_OF_MSG, toastText);
		msg.setData(data);
		msg.what = SHOW_DIALOG;
		
		mHandler.sendMessage(msg);
	}
	
	public void finishDialogSuccessDone(){
			
		mHandler.sendEmptyMessage(CLOSE_DIALOG_SUCCESS);
	}
	
	public void finishDialogWithErrorMsg() {
		
		mHandler.sendEmptyMessage(CLOSE_DIALOG_ERROR);
	}
	
	private void showLoadingDialog(String msg) {

		if (null != mDialog && !mDialog.isShow()) {
			
			mDialog.showDialog(R.id.tv_loading_dialog_msg, msg);
		}
	}

	private void finishDialog() {

		if (null != mDialog && mDialog.isShow()) {

			mDialog.dismissDialog();
		}
	}

	public ILoadingDialogCallback getCallback() {
		return mCallback;
	}

	public void setCallback(ILoadingDialogCallback mCallback) {
		this.mCallback = mCallback;
	}
}
